import * as SkeletonUtils from 'three/examples/jsm/utils/SkeletonUtils.js';

function chuLiMoXing(listener, audioLoader, diTu, ren, qiangSheng) {

	let changJingObj = [];
	let jueSeObj = new Map();

	let weiZhi = [{
			x: -8,
			y: 3,
			z: 33
		}, {
			x: -10,
			y: 3,
			z: 33
		}, {
			x: -12,
			y: 3,
			z: 33
		}, {
			x: -6,
			y: 3,
			z: 33
		}, {
			x: -4,
			y: 3,
			z: 33
		},
		{
			x: 8,
			y: -0.4,
			z: -22
		}, {
			x: 10,
			y: -0.4,
			z: -22
		}, {
			x: 12,
			y: -0.4,
			z: -22
		}, {
			x: 6,
			y: -0.4,
			z: -22
		}, {
			x: 4,
			y: -0.4,
			z: -22
		}
	];

	//多材质mesh会被分割
	//scene.add添加object 原本父元素丢失 局部坐标变世界坐标、缩放失效
	//非破碎物体结构 包 -> 碰撞mesh和显示mesh
	//blender 物体名 jing_bao || dong_bao -> pengZhuang xianShi
	//可破碎物体结构 sui_xianShi
	//SkinnedMesh的显示取决于 parent的原点是否在camera里

	function traverse(object) {
	
		let children = [...object.children]; //scene.add()的时会从parent的数组中删除 不拷贝数组index不准
	
		for (let i = 0; i < children.length; i++) {
	
			let obj = children[i];
	
			if (obj.name.indexOf('bao') > -1 || obj.name.indexOf('sui') > -1) {
				changJingObj.push(obj);
			}
			
			//多材质mesh会被分割成子mesh
			if (obj.name.indexOf('xianShi') > -1 || obj.parent.name.indexOf('xianShi') > -1) {
				obj.castShadow = true;
				obj.receiveShadow = true;
			}
	
			if (obj.children.length > 0) traverse(obj);
	
		}
	}

	traverse(diTu.scene);

	//角色
	
	function chuanTou(a, callback) {
		callback(a);
		let b = [...a.children];
		for (let i = 0; i < b.length; i++) chuanTou(b[i], callback);
	}
	
	let model = ren.scene;

	for (let i = 0; i < 10; i++) {

		let model1 = SkeletonUtils.clone(model);

		chuanTou(model1, obj => {

			obj.userData.jueSeHao = i + 1;

			if (obj.name.indexOf('bao') > -1) {

				const animations = ren.animations;
				let mixer = new THREE.AnimationMixer(obj);

				let position = new THREE.Vector3(weiZhi[i].x, weiZhi[i].y, weiZhi[i].z);

				obj.position.copy(position);

				obj.userData.chuShengDian = position;
				obj.userData.xueLiang = 100;
				obj.userData.mixer = mixer;
				obj.userData.dongZuo = {
					zhan: mixer.clipAction(animations[1]),
					pao: mixer.clipAction(animations[0])
				};

				jueSeObj.set(i + 1, obj);
				
				//枪声
				obj.userData.qiangShengBuffer = qiangSheng;

			}

			if (obj.name.indexOf('xianShi') > -1 || (obj.parent && obj.parent.name
					.indexOf('xianShi') > -1)) {
				obj.castShadow = true;
				obj.receiveShadow = true;
			}
			
			if (obj.name.includes('xiong')) obj.parent.parent.parent.parent.userData.xiongBone = obj;
			if (obj.name.includes('shiDian')) {
				obj.visible = false;
				obj.parent.userData.shiDianObj = obj;
			};
			
		})
	}

	return {
		changJingObj,
		jueSeObj
	}
}


export default chuLiMoXing;
